package com.intelligent.system.common.utils;

import com.intelligent.system.common.exception.CustomException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * 文件下载工具类
 */
@Slf4j
public class FileDownloadUtils {

    /**
     * 下载文件
     *
     * @param filePath 文件路径
     * @param fileName 下载时的文件名
     * @return ResponseEntity
     */
    public static ResponseEntity<byte[]> download(String filePath, String fileName) {
        try {
            Path path = Paths.get(filePath);
            if (!Files.exists(path)) {
                throw new CustomException("文件不存在", 404);
            }

            byte[] data = Files.readAllBytes(path);
            String mimeType = Files.probeContentType(path);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
                    .header(HttpHeaders.CONTENT_TYPE, mimeType)
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length))
                    .body(data);
        } catch (IOException e) {
            log.error("文件下载失败", e);
            throw new CustomException("文件下载失败: " + e.getMessage(), 500);
        }
    }

    /**
     * 下载文件（使用原始文件名）
     *
     * @param filePath 文件路径
     * @return ResponseEntity
     */
    public static ResponseEntity<byte[]> download(String filePath) {
        Path path = Paths.get(filePath);
        String fileName = path.getFileName().toString();
        return download(filePath, fileName);
    }

    /**
     * 预览文件（在线打开）
     *
     * @param filePath 文件路径
     * @return ResponseEntity
     */
    public static ResponseEntity<byte[]> preview(String filePath) {
        try {
            Path path = Paths.get(filePath);
            if (!Files.exists(path)) {
                throw new CustomException("文件不存在", 404);
            }

            byte[] data = Files.readAllBytes(path);
            String mimeType = Files.probeContentType(path);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_TYPE, mimeType)
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(data.length))
                    .body(data);
        } catch (IOException e) {
            log.error("文件预览失败", e);
            throw new CustomException("文件预览失败: " + e.getMessage(), 500);
        }
    }

    /**
     * 下载文件（支持断点续传）
     *
     * @param filePath 文件路径
     * @param fileName 下载时的文件名
     * @param range 请求头中的Range值
     * @return ResponseEntity
     */
    public static ResponseEntity<byte[]> downloadWithRange(String filePath, String fileName, String range) {
        try {
            Path path = Paths.get(filePath);
            if (!Files.exists(path)) {
                throw new CustomException("文件不存在", 404);
            }

            long fileSize = Files.size(path);
            long start = 0;
            long end = fileSize - 1;

            if (range != null && range.startsWith("bytes=")) {
                String[] ranges = range.substring(6).split("-");
                start = Long.parseLong(ranges[0]);
                if (ranges.length > 1) {
                    end = Long.parseLong(ranges[1]);
                }
            }

            long contentLength = end - start + 1;
            byte[] data = Files.readAllBytes(path);
            String mimeType = Files.probeContentType(path);

            return ResponseEntity.status(206)
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
                    .header(HttpHeaders.CONTENT_TYPE, mimeType)
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength))
                    .header(HttpHeaders.CONTENT_RANGE, String.format("bytes %d-%d/%d", start, end, fileSize))
                    .body(data);
        } catch (IOException e) {
            log.error("文件下载失败", e);
            throw new CustomException("文件下载失败: " + e.getMessage(), 500);
        }
    }

    /**
     * 获取文件下载的ResponseEntity（支持大文件）
     *
     * @param filePath 文件路径
     * @param fileName 下载时的文件名
     * @return ResponseEntity
     */
    public static ResponseEntity<Path> downloadLargeFile(String filePath, String fileName) {
        try {
            Path path = Paths.get(filePath);
            if (!Files.exists(path)) {
                throw new CustomException("文件不存在", 404);
            }

            String mimeType = Files.probeContentType(path);
            long fileSize = Files.size(path);

            return ResponseEntity.ok()
                    .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fileName)
                    .header(HttpHeaders.CONTENT_TYPE, mimeType)
                    .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileSize))
                    .body(path);
        } catch (IOException e) {
            log.error("文件下载失败", e);
            throw new CustomException("文件下载失败: " + e.getMessage(), 500);
        }
    }
} 